package com.zrl.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrl.project.common.ErrorCode;
import com.zrl.project.common.UserHolder;
import com.zrl.project.constant.CommonConstant;
import com.zrl.project.exception.BusinessException;
import com.zrl.project.model.VO.blogVO.BlogAndUserInfoVO;
import com.zrl.project.model.VO.blogVO.BlogOrder;
import com.zrl.project.model.VO.blogVO.CommentWithBLogAndUserInfoVo;
import com.zrl.project.model.entity.*;
import com.zrl.project.model.request.CommentSearchRequest;
import com.zrl.project.service.BlogService;
import com.zrl.project.mapper.BlogMapper;
import com.zrl.project.service.CommentService;
import com.zrl.project.service.LikesService;
import com.zrl.project.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 13168
* @description 针对表【blog(博客表)】的数据库操作Service实现
* @createDate 2023-03-22 03:36:59
*/
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog>
    implements BlogService{

    @Resource
    private UserService userService;

    @Resource
    private CommentService commentService;

    @Resource
    private LikesService likesService;


    @Override
    public BlogAndUserInfoVO getBlogAndUserInfo(Long id) {

        //查询出博客信息
        LambdaQueryWrapper<Blog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Blog::getId,id);
        Blog blog = getOne(queryWrapper);

        return getBlogUserInfoVO(blog);
    }

    private BlogAndUserInfoVO getBlogUserInfoVO(Blog blog) {

        //查询评论数量
        LambdaQueryWrapper<Comment> commentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        commentLambdaQueryWrapper.eq(Comment::getBlogId,blog.getId());
        long commentCount = commentService.count(commentLambdaQueryWrapper);


        LambdaQueryWrapper<Likes> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Likes::getBlogId,blog.getId());
        Long likesCount = likesService.count(queryWrapper);

        //根据用户id查询用户信息
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        //将用户名称和用户头像,评论数量，点赞数量加入到BlogUserInfoVO中
        BlogAndUserInfoVO blogUserInfoVO = new BlogAndUserInfoVO();
        BeanUtils.copyProperties(blog,blogUserInfoVO);
        blogUserInfoVO.setUserName(user.getUserName());
        blogUserInfoVO.setUserAvatar(user.getUserAvatar());
        blogUserInfoVO.setCommentsCount(commentCount);
        blogUserInfoVO.setLikes(likesCount);

        return blogUserInfoVO;
    }


    @Override
    public List<BlogAndUserInfoVO> searchBlogs(BlogOrder blog) {


        LambdaQueryWrapper<Blog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Blog::getCreateTime);

        return getBlogAndUserInfoVOList(blog, queryWrapper);
    }



    @Override
    @Transactional
    public boolean deleteBlog(Long id) {
        //根据博客id删除评论
        LambdaQueryWrapper<Comment> commentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        commentLambdaQueryWrapper.eq(Comment::getBlogId,id);
        List<Comment> list = commentService.list(commentLambdaQueryWrapper);
        if (list.size() != 0){
            boolean removeComment = commentService.remove(commentLambdaQueryWrapper);
            if (!removeComment){
                throw new BusinessException(ErrorCode.OPERATION_ERROR,"删除评论步骤失败");
            }
        }


        //根据博客id删除喜欢
        LambdaQueryWrapper<Likes> likesLambdaQueryWrapper = new LambdaQueryWrapper<>();
        likesLambdaQueryWrapper.eq(Likes::getBlogId,id);
        List<Likes> questionLikes = likesService.list(likesLambdaQueryWrapper);
        if (questionLikes.size() != 0){
            boolean removeLikes = likesService.remove(likesLambdaQueryWrapper);
            if (!removeLikes){
                throw new BusinessException(ErrorCode.OPERATION_ERROR,"删除喜欢步骤失败");
            }
        }
        //删除博客
        LambdaQueryWrapper<Blog> blogLambdaQueryWrapper = new LambdaQueryWrapper<>();
        blogLambdaQueryWrapper.eq(Blog::getId,id);
        return remove(blogLambdaQueryWrapper);
    }


    /**
     * 获取博客信息
     * @param blog 博客搜索条件
     * @param queryWrapper 查询条件
     * @return
     */
    private List<BlogAndUserInfoVO> getBlogAndUserInfoVOList(BlogOrder blog, LambdaQueryWrapper<Blog> queryWrapper) {


        List<BlogAndUserInfoVO> result = new ArrayList<>();
        //如果要查询我的博客
        Long userId = blog.getUserId();
        if (blog.getUserId() != null){
            queryWrapper.eq(Blog::getUserId,userId);

            List<BlogAndUserInfoVO> blogAndUserInfoVOS = list(queryWrapper)
                    .stream()
                    .map(this::getBlogUserInfoVO)
                    .collect(Collectors.toList());

            return blogAndUserInfoVOS.stream()
                    .sorted(Comparator.comparing(BlogAndUserInfoVO::getCommentsCount).reversed())
                    .sorted(Comparator.comparing(BlogAndUserInfoVO::getLikes).reversed()).collect(Collectors.toList());

        }

        //如果要查询精选博客
        String order = blog.getOrder();
        if (CommonConstant.GOOD.equals(order)){
            queryWrapper.eq(Blog::getPriority,CommonConstant.TOP);
        }

        String content = blog.getContent();
        if (StringUtils.isNotBlank(content)) {
            queryWrapper.and(blogLambdaQueryWrapper -> {
                blogLambdaQueryWrapper.like(Blog::getContent, content)
                        .or()
                        .like(Blog::getTitle, content)
                        .or()
                        .like(Blog::getDescription, content);
            });
        }

        List<BlogAndUserInfoVO> blogAndUserInfoVOS = list(queryWrapper)
                .stream()
                .map(this::getBlogUserInfoVO)
                .collect(Collectors.toList());


        if (CommonConstant.HOT.equals(order)){
            return blogAndUserInfoVOS.stream()
                    .sorted(Comparator.comparing(BlogAndUserInfoVO::getCommentsCount).reversed())
                    .sorted(Comparator.comparing(BlogAndUserInfoVO::getLikes).reversed())
                    .collect(Collectors.toList());

        }

        return blogAndUserInfoVOS;
    }



    @Override
    public List<CommentWithBLogAndUserInfoVo> queryAllComments(CommentSearchRequest commentSearchRequest) {

        List<Comment> list = new ArrayList<>();

        if (commentSearchRequest == null){
            list = commentService.list();
        }else {
            LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.orderByDesc(Comment::getCreateTime);
            Long userId = commentSearchRequest.getUserId();
            Long blogId = commentSearchRequest.getBlogId();
            Long questionId = commentSearchRequest.getQuestionId();
            String content = commentSearchRequest.getContent();
            if (userId != null){
                queryWrapper.eq(Comment::getUserId,userId);
            }
            if (blogId != null){
                queryWrapper.eq(Comment::getBlogId,blogId);
            }
            if (questionId != null){
                queryWrapper.eq(Comment::getQuestionId,questionId);
            }
            if (StringUtils.isNotBlank(content)){
                queryWrapper.like(Comment::getContent,content);
            }

             list = commentService.list(queryWrapper);
        }
        return list.stream().map(comment -> {
            CommentWithBLogAndUserInfoVo commentWithBLogAndUserInfoVo = new CommentWithBLogAndUserInfoVo();
            BeanUtils.copyProperties(comment,commentWithBLogAndUserInfoVo);

            //查询博客标题和用户名称
            User user = userService.getById(comment.getUserId());
            commentWithBLogAndUserInfoVo.setUserName(user.getUserName());

            if (comment.getBlogId() != 0){
                Blog blog = getById(comment.getBlogId());
                commentWithBLogAndUserInfoVo.setBlogTitle(blog.getTitle());
            }

            return commentWithBLogAndUserInfoVo;

        }).collect(Collectors.toList());
    }

    @Override
    public List<BlogAndUserInfoVO> getMyStartBlog() {

        Long id = UserHolder.getUser().getId();
        if (id == null){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"未登录");
        }
        LambdaQueryWrapper<Likes> likesLambdaQueryWrapper = new LambdaQueryWrapper<>();
        likesLambdaQueryWrapper.eq(Likes::getUserId,id);
        List<Likes> list = likesService.list(likesLambdaQueryWrapper);
        if (list==null||list.isEmpty()){
            return Collections.emptyList();
        }
        List<Long> blogIdList = list
                .stream()
                .map(Likes::getBlogId)
                .collect(Collectors.toList());

        System.out.println(blogIdList);
        return blogIdList.stream()
                .map(this::getBlogAndUserInfo)
                .collect(Collectors.toList());
    }
}




